<?php 
require_once 'config.php'; 
require_once 'startup.php'; 
require_once APP_DIR . 'json.php';
require_once APP_DIR . 'image.php'; 

// Check for user login
if(!$user->isLogged()){ 
    header('Location: ' . $config['url_admin'] . 'login.php');    
    exit();
}

$image_path = ADMIN_DIR . 'image/data/';
$image_url = $config['url_admin'] . 'image/data/';
if(!file_exists($image_path . 'cache/')){
    @mkdir($image_path . 'cache/', 0777);
}
    
if(isset($request->get['type'])){
    switch($request->get['type']){
        case 'directory':
            echo directory();
            break;            
        case 'files':
            echo files();
            break;
        case 'create':
            echo create();
            break;   
        case 'delete':
            echo delete();
            break; 
        case 'folders':
            echo folders();
            break; 
        case 'move':
            echo move();
            break;
        case 'copy':
            echo copyFile();
            break;
        case 'rename':
            echo renameFile();
            break;
        case 'upload':
            echo upload();
            break;
    }
                       
    exit();
}

function directory() {  
    global $image_path, $request;   
    $json = array();
    
    if(isset($request->post['directory'])){        
        $directories = glob(rtrim($image_path . str_replace('../', '', $request->post['directory']), '/') . '/*', GLOB_ONLYDIR);         
        if($directories){
            $i = 0;
        
            foreach ($directories as $directory) {
                $dir = basename($directory);
                if($dir != 'cache' && $dir != 'filemanager'){
                    $json[$i]['data'] = $dir; //basename($directory);
                    $json[$i]['attributes']['directory'] = substr($directory, strlen($image_path));                 
                    $children = glob(rtrim($directory, '/') . '/*', GLOB_ONLYDIR);                   
                    if($children){
                        $json[$i]['children'] = ' ';
                    }
                    
                    $i++;
                }
            }
        }        
    }
    
    return Json::encode($json);        
}    

function files() {
    global $image_path, $request;
    $json = array();    
    
    if(isset($request->post['directory']) && $request->post['directory']){
        $directory = $image_path . str_replace('../', '', $request->post['directory']);
    } 
    else{
        $directory = $image_path;
    }
    
    $allowed = array(
        '.jpg',
        '.jpeg',
        '.png',
        '.gif'
    );
    
    $files = glob(rtrim($directory, '/') . '/*');  
    foreach ($files as $file){
        if(is_file($file)){
            $ext = strrchr($file, '.');
        } 
        else{
            $ext = '';
        }    
        
        if(in_array(strtolower($ext), $allowed)){
            $size = filesize($file); 
            $i = 0;   
            $suffix = array(
                'B',
                'KB',
                'MB',
                'GB',
                'TB',
                'PB',
                'EB',
                'ZB',
                'YB'
            );

            while (($size / 1024) > 1) {
                $size = $size / 1024;
                $i++;
            }
                
            $json[] = array(
                'file'     => substr($file, strlen($image_path)),
                'filename' => basename($file),
                'size'     => round(substr($size, 0, strpos($size, '.') + 4), 2) . $suffix[$i],
                'thumb'    => resize(substr($file, strlen($image_path)), 100, 100)
            );
        }
    }
    
    return Json::encode($json);    
}    

function create() {
    global $image_path, $request; 
    $json = array();
    
    if(isset($request->post['directory'])){ 
        if(isset($request->post['name']) || $request->post['name']){
            $directory = rtrim($image_path . str_replace('../', '', $request->post['directory']), '/');                               
            
            if (!is_dir($directory)) {
                $json['error'] = 'Warning: Please select a directory!';
            }
            
            if (file_exists($directory . '/' . str_replace('../', '', $request->post['name']))) {
                $json['error'] = 'Warning: A file or directory with the same name already exists!';
            }
        } 
        else {
            $json['error'] = 'Warning: Please enter a new name!';
        }   
    } 
    else {
        $json['error'] = 'Warning: Please select a directory!';
    }
    
    if (!isset($json['error'])) {    
        mkdir($directory . '/' . str_replace('../', '', $request->post['name']), 0777);
        
        $json['success'] ='Success: Directory created!';
    }    
    
    
    return Json::encode($json);
}
    
function delete() {
    global $image_path, $request;
    $json = array();
    
    if(isset($request->post['path'])){
        $path = rtrim($image_path . str_replace('../', '', $request->post['path']), '/');
         
        if(!file_exists($path)){
            $json['error'] = 'Warning: Please select a directory or file!';
        }
        
        if($path == rtrim($image_path, '/')){
            $json['error'] = 'Warning: You can not delete this directory!';
        }
    } 
    else{
        $json['error'] = 'Warning: Please select a directory or file!';
    }
      
    if(!isset($json['error'])){
        if(is_file($path)){
            unlink($path);
        } 
        elseif(is_dir($path)){
            recursiveDelete($path);
        }
        
        $json['success'] = 'Success: Your file or directory has been deleted!';
    }                
    
    return Json::encode($json);
}

function recursiveDelete($directory){
    if(is_dir($directory)){
        $handle = opendir($directory);
    }
        
    if(!$handle){
        return false;
    }
        
    while(false !== ($file = readdir($handle))){
        if($file != '.' && $file != '..'){
            if (!is_dir($directory . '/' . $file)){
                unlink($directory . '/' . $file);
            } 
            else{
                $this->recursiveDelete($directory . '/' . $file);
            }
        }
    }
        
    closedir($handle);
    rmdir($directory);
     
    return true;
}
    
function folders(){
    global $image_path, $request;
    
    return recursiveFolders($image_path);    
}
    
function recursiveFolders($directory){
    global $image_path;
    
    $output = '';
    $dir = basename($directory);
    if($dir != 'cache' && $dir != 'filemanager'){
        $output .= '<option value="' . substr($directory, strlen($image_path)) . '">' . substr($directory, strlen($image_path)) . '</option>';
            
        $directories = glob(rtrim(str_replace('../', '', $directory), '/') . '/*', GLOB_ONLYDIR);
            
        foreach ($directories  as $directory) {
            $output .= recursiveFolders($directory);
        }
    }
        
    return $output;
}
    
function move() {
    global $image_path, $request;
    $json = array();
        
    if(isset($request->post['from']) && isset($request->post['to'])){
        $from = rtrim($image_path . str_replace('../', '', $request->post['from']), '/');            
        if(!file_exists($from)) {
            $json['error'] = 'Warning: File or directory does not exist!';
        }                                                                                                                                                                         
        if($from == $image_path){
            $json['error'] = 'Warning: Can not alter your default directory!';
        }
            
        $to = rtrim($image_path . str_replace('../', '', $request->post['to']), '/');
        if(!file_exists($to)){
            $json['error'] = 'Warning: Move to directory does not exists!';
        }    
        if(file_exists($to . '/' . basename($from))){
            $json['error'] = 'Warning: A file or directory with the same name already exists!';
        }
    } 
    else{
        $json['error'] = 'Warning: Please select a directory!';
    }
    
    if(!isset($json['error'])){
        rename($from, $to . '/' . basename($from));
        $json['success'] = 'Success: Your file or directory has been moved!';
    }
        
    return Json::encode($json);
}    
    
function copyFile(){
    global $image_path, $request;    
    $json = array();
        
    if(isset($request->post['path']) && isset($request->post['name'])){
        if((strlen(utf8_decode($request->post['name'])) < 3) || (strlen(utf8_decode($request->post['name'])) > 255)){
            $json['error'] = 'Warning: Filename must be a between 3 and 255!';
        }
        
        $old_name = rtrim($image_path . str_replace('../', '', $request->post['path']), '/');
        if(!file_exists($old_name) || $old_name == $image_path){
            $json['error'] = 'Warning: Can not copy this file or directory!';
        }
        if(is_file($old_name)){
            $ext = strrchr($old_name, '.');
        } 
        else{
            $ext = '';
        }        
            
        $new_name = dirname($old_name) . '/' . str_replace('../', '', $request->post['name'] . $ext);
        if(file_exists($new_name)){
            $json['error'] = 'Warning: A file or directory with the same name already exists!';
        }            
    } 
    else {
        $json['error'] = 'Warning: Please select a directory or file!';
    }
        
    if(!isset($json['error'])){
        if(is_file($old_name)){
            copy($old_name, $new_name);
        }
        else{
            recursiveCopy($old_name, $new_name);
        }
            
        $json['success'] = 'Success: Your file or directory has been moved!';
    }
        
    return Json::encode($json);    
}

function recursiveCopy($source, $destination) { 
    $directory = opendir($source); 
    @mkdir($destination); 
        
    while(false !== ($file = readdir($handle))){
        if(($file != '.') && ($file != '..')){ 
            if(is_dir($source . '/' . $file)) { 
                recursiveCopy($source . '/' . $file, $destination . '/' . $file); 
            } 
            else{ 
                copy($source . '/' . $file, $destination . '/' . $file); 
            } 
        } 
    } 
        
    closedir($directory); 
} 
  
function renameFile(){
    global $image_path, $request;    
    $json = array();
        
    if(isset($request->post['path']) && isset($request->post['name'])){
        if((strlen(utf8_decode($request->post['name'])) < 3) || (strlen(utf8_decode($request->post['name'])) > 255)){
            $json['error'] = 'Warning: Filename must be a between 3 and 255!';
        }
                
        $old_name = rtrim($image_path . str_replace('../', '', $request->post['path']), '/');
        if(!file_exists($old_name) || $old_name == $image_path){
            $json['error'] = 'Warning: Can not rename this directory!';
        }
            
        if(is_file($old_name)){
            $ext = strrchr($old_name, '.');
        }
        else{
            $ext = '';
        }        
            
        $new_name = dirname($old_name) . '/' . str_replace('../', '', $request->post['name'] . $ext);
        if(file_exists($new_name)){
            $json['error'] = 'Warning: A file or directory with the same name already exists!';
        }            
    }
        
    if(!isset($json['error'])) {
        rename($old_name, $new_name);             
        $json['success'] = 'Success: Your file or directory has been renamed!';
    }
        
    return Json::encode($json);
}
    
function upload(){
    global $image_path, $request;
    $json = array();
        
    if(isset($request->post['directory'])){           
        if(isset($request->files['image']) && $request->files['image']['tmp_name']){             
            if((strlen(utf8_decode($request->files['image']['name'])) < 3) || (strlen(utf8_decode($request->files['image']['name'])) > 255)){
                $json['error'] = 'Warning: Filename must be a between 3 and 255!';
            }
            
            $directory = rtrim($image_path . str_replace('../', '', $request->post['directory']), '/');
            if(!is_dir($directory)){
                $json['error'] = 'Warning: Please select a directory!';
            }
            if($request->files['image']['size'] > 300000){
                $json['error'] = 'Warning: File to big please keep below 300kb and no more than 1000px height or width!';
            }
                
            $allowed = array(
                'image/jpeg',
                'image/pjpeg',
                'image/png',
                'image/x-png',
                'image/gif',
                'application/x-shockwave-flash'
            );
                        
            if(!in_array($request->files['image']['type'], $allowed)){
                $json['error'] = 'Warning: Incorrect file type!';
            }
                
            $allowed = array(
                '.jpg',
                '.jpeg',
                '.gif',
                '.png',
                '.flv'
            );
            if (!in_array(strtolower(strrchr($request->files['image']['name'], '.')), $allowed)){
                $json['error'] = 'Warning: Incorrect file type!';
            }
            if ($request->files['image']['error'] != UPLOAD_ERR_OK) {
                $json['error'] = 'error_upload_' . $request->files['image']['error'];
            }            
        }
        else{
            $json['error'] = 'Warning: Please select a file!';
        }
    }
    else{
        $json['error'] = 'Warning: Please select a directory!';
    }
        
    if(!isset($json['error'])){    
        if(@move_uploaded_file($request->files['image']['tmp_name'], $directory . '/' . basename($request->files['image']['name']))){
            $json['success'] = 'Success: Your file has been uploaded!';
        }
        else{
            $json['error'] = 'Warning: File could not be uploaded for an unknown reason!';
        }
    }
        
    return Json::encode($json);
}
      
function resize($filename, $width, $height){
    global $image_path, $image_url, $request;
    
    if(!file_exists($image_path . $filename) || !is_file($image_path . $filename)) {   
        return;
    } 
                
    $info = pathinfo($filename);
    $extension = $info['extension'];    
    $old_image = $filename;
    
    if(!file_exists($image_path . 'cache/')){
        @mkdir($image_path . 'cache/', 0777);
    }
    $new_image = 'cache/' . substr($filename, 0, strrpos($filename, '.')) . '-' . $width . 'x' . $height . '.' . $extension;
    
    if (!file_exists($image_path . $new_image) || (filemtime($image_path . $old_image) > filemtime($image_path . $new_image))) {
        $path = '';
        
        $directories = explode('/', dirname(str_replace('../', '', $new_image)));
        
        foreach ($directories as $directory) {
            $path = $path . '/' . $directory;
            
            if (!file_exists($image_path . $path)) {
                @mkdir($image_path . $path, 0777);
            }        
        }
        
        $image = new Image($image_path . $old_image);
        $image->resize($width, $height);
        $image->save($image_path . $new_image);
    }
    
    if(isset($request->server['HTTPS']) && (($request->server['HTTPS'] == 'on') || ($request->server['HTTPS'] == '1'))){
        return $image_url . $new_image;
    } 
    else {
        return $image_url . $new_image;
    }    
}